//
//  AppDelegate.m
//  Diary
//
//  Created by lanou3g on 15/12/19.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "AppDelegate.h"
#import "DiaryViewController.h"
#import "MoodViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "DiaryViewController.h"
#import "RootViewController.h"

//友盟
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"

#import "iflyMSC/IFlyMSC.h"
#import "UMSocial.h"
//引导页相关宏定义
#define kScrenFrame_Width [UIScreen mainScreen].bounds.size.width
#define kScrenFrame_Height [UIScreen mainScreen].bounds.size.height

@interface AppDelegate ()<UIScrollViewDelegate>

{
    
    NSTimer *_nsTimer;   //引导页计时器
    
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    RootViewController *root = [[RootViewController alloc]init];
    self.window.rootViewController = root;

    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSInteger myInteger = [userDefaultes integerForKey:@"myInteger"];
    
    if (myInteger == 100) {
        // 手势解锁相关
        NSString* pswd = [LLLockPassword loadLockPassword];
        if (pswd) {
            [self showLLLockViewController:LLLockViewTypeCheck];
        } else {
            [self showLLLockViewController:LLLockViewTypeCreate];
        }
    }
    
    
    
    
    ///友盟appKay
    [UMSocialData setAppKey:@"56999c22e0f55abee600155f"];
    
    
    [UMSocialQQHandler setQQWithAppId:@"1105045283" appKey:@"1PwSCBikLsRX9Sh8" url:@"http://www.umeng.com/social"];
    
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:@"wx8d645097eacdf203" appSecret:@"ef9dae5d6244513861730c45629b6a06" url:@"http://www.umeng.com/social"];
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",@"	569a36f3"];
    [IFlySpeechUtility createUtility:initString];
    
    [self guide];
    
    return YES;
}

- (void)guide{
    
    // NSUserDefaults用于存储一些短小的信息
    //创建NSUserDefaults对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //第一次进入,显示导航页面
    if (NO == [defaults boolForKey:@"first"]) {
        [self allViews];
        //给pageControl添加点击事件
        [self.pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:UIControlEventValueChanged ];
        
        //给scrollView设置代理
        self.scrollView.delegate = self;
        
        //给scrollView最后一张图片添加手势(移除导航页面)
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGRAction:)];
        self.imageView.userInteractionEnabled = YES;
        [self.imageView addGestureRecognizer:tapGR];
        
        //改变值(设置值)
        [defaults setBool:YES forKey:@"first"];
        [defaults synchronize];
    } else {
        
        self.imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"11.jpg"]];
        self.imageView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        [self.window addSubview:self.imageView];
        
        
        _nsTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(jump) userInfo:nil repeats:NO];
        //        [_nsTimer fire];
    }

    
}



///添加引导页
-(void)allViews
{
    
    //scrollView
    self.scrollView = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.scrollView.contentSize = CGSizeMake(kScrenFrame_Width*4, kScrenFrame_Height);
    //设置一页一页的切换
    self.scrollView.pagingEnabled = YES;
    //自定义方法:添加图片
    [self addImageViews];
    
    [self.window addSubview:self.scrollView];
    
    
    //UIPageControl
    //1.创建对象
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
    self.pageControl.center = CGPointMake(kScrenFrame_Width / 2, kScrenFrame_Height - 50);
    //2.配置属性
    //    self.pageControl.backgroundColor = [UIColor greenColor];
    //(1.设置page个数
    self.pageControl.numberOfPages = 4;
    //(2.设置当前点得颜色
    self.pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
    //(3.设置其他点得颜色
    self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    //(4.设置当前点
    self.pageControl.currentPage = self.scrollView.contentOffset.x/kScrenFrame_Width;
    //3.添加到父视图
    [self.window addSubview:self.pageControl];
    
    
}

#pragma mark - 给引导页scrollView添加图片
-(void)addImageViews
{
    
    for (int i = 0; i<4; i++) {
        //实例化imageView添加到scrollView
        UIImageView *imageview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg",i+1]]];
        //设置frame
        imageview.frame = CGRectMake(kScrenFrame_Width * i, 0, kScrenFrame_Width, kScrenFrame_Height);
        //最后一张需要添加手势,去控制器添加手势
        if (i == 3) {
            self.imageView = imageview;
        }
        [self.scrollView addSubview:imageview];
    }
    
}



- (void)applicationWillResignActive:(UIApplication *)application {
   
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSInteger myInteger = [userDefaultes integerForKey:@"myInteger"];
    
    if (myInteger == 100) {
        // 手势解锁相关
        NSString* pswd = [LLLockPassword loadLockPassword];
        if (pswd) {
            [self showLLLockViewController:LLLockViewTypeCheck];
        } else {
            [self showLLLockViewController:LLLockViewTypeCreate];
        }
    }
    
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    
    

    
}


/****************以下为添加引导页相关方法实现*****************/

- (void)applicationDidBecomeActive:(UIApplication *)application {
    

    
}


-(void)jump
{
    
    [self.imageView removeFromSuperview];
    
    
}


#pragma mark - 给引导页pageControl添加点击事件
-(void)pageControlAction:(UIPageControl *)sender
{
    
    
    NSInteger num = sender.currentPage;
    //改变scrollView的偏移量
    self.scrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width * num, 0);
    
}

#pragma mark - 实现方法--UIScrollViewDelegate
//结束减速
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    //设置pageControl.currentPage
    self.pageControl.currentPage = self.scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width;
    
}


#pragma mark - tapGR点击事件
-(void)tapGRAction:(UITapGestureRecognizer *)sender
{
    
    //移除导航页面
    [self.scrollView removeFromSuperview];
    [self.pageControl removeFromSuperview];
    
}

/****************以上为添加引导页相关方法实现*****************/


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - 弹出手势解锁密码输入框
- (void)showLLLockViewController:(LLLockViewType)type
{
        if(self.window.rootViewController.presentingViewController == nil){
        
        LLLog(@"root = %@", self.window.rootViewController.class);
        LLLog(@"lockVc isBeingPresented = %d", [self.lockVc isBeingPresented]);
        
        self.lockVc = [[LLLockViewController alloc] init];
        self.lockVc.nLockViewType = type;
        
        self.lockVc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        
        [self.window.rootViewController presentViewController:self.lockVc animated:NO completion:^{
        }];
        LLLog(@"创建了一个pop=%@", self.lockVc);
    }
}

- (void)mima{
    
    
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.Diary" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Diary" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Diary.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
       
       
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            
            abort();
        }
    }
}

@end
